<?php

class CaptchaController extends BaseController {
        
    public function indexAction($requestData) {
    	$src = DOC_ROOT . "/webroot/captcha.txt";    	
    	$source = file_get_contents($src);
    	$test = "/\s([^\s]*)\s/";
    	preg_match_all($test, $source, $captchas);
    	$choices = array();
    	foreach($captchas[0] as $c) {
    		$x = trim($c);
    		$hash = md5(strtolower($x));
    		if(isset($choices[$hash])) continue;
    		if(is_numeric($x)) continue;
    		
    		if(isset($c[5])) {
    			$choices[$hash] = $x;
    		}
    	}
    	shuffle($choices);
    	
		$string = strtolower($choices[0]);
		if(isset($string[10])) {
			$string = substr($string, 0, 10);
		}
		
		$font = 'fonts/You Are Loved.ttf';
		$captcha = imagecreatefrompng("./captcha.png");
		$grey = imagecolorallocate($captcha, 100, 100, 100);
		
		$x = (200 - (strlen($string)*19))/2; 
		imagettftext($captcha, 30, 0, $x, rand(45, 55), $grey, $font, $string);

		$_SESSION['key'] = md5($string);
		
		#Output the image
		header("Content-type: image/png");
		imagepng($captcha);
		imagedestroy($captcha);

    	exit;
    }
    
    public static function validateCaptcha($captcha) {
    	return ($_SESSION['key'] == md5($captcha));
    }

}

?>